package com.gary.memoryLeak;

import java.util.Arrays;

/**
 * @author peng_rui
 * @date 2022/3/13
 */
public class CustomStack {
    private Object[] arr;
    private int size;
    private int INIT_CAPACITY = 16;

    public CustomStack() {
        this.arr = new Object[INIT_CAPACITY];
    }

    /**
     * 入栈
     * 没毛病
     * @param obj
     */
    public void push(Object obj) {
        //扩容
        if (size == arr.length) {
            extendStack();
        }
        arr[size++] = obj;
    }

    /**
     * 有毛病的pop
     * 问题处在与 arr[--size]
     *  pop之后未将其位置的引用消除，导致内存泄露
     */
    public Object pop() throws IllegalAccessException {
        if (size == 0) {
            throw new IllegalAccessException("空");
        }
        return arr[--size];
    }

    public Object popOk() throws IllegalAccessException {
        if (size == 0) {
            throw new IllegalAccessException("空");
        }
        Object obj = arr[--size];
        arr[size] = null;
        return obj;
    }

    private void extendStack() {
        arr = Arrays.copyOf(arr, (int) (arr.length * 1.5));
    }
}
